#include <jni.h>
#include "ffmpeg.h"
#include "android_log.h"
#include "ffmpeg_thread.h"


static JavaVM *jvm = NULL;
//java虚拟机
static jclass m_clazz = NULL;//当前类(面向java)
JNIEnv *envs = NULL;

/**
 * 回调执行Java方法
 * 参看 Jni反射+Java反射
 */
void callJavaMethod(JNIEnv *env, jclass clazz,int ret) {
    if (clazz == NULL) {
        LOGE("---------------clazz isNULL---------------");
        return;
    }
    //获取方法ID (I)V指的是方法签名 通过javap -s -public FFmpegCmd 命令生成
    jmethodID methodID = (*env)->GetStaticMethodID(env, clazz, "onExecuted", "(I)V");
    if (methodID == NULL) {
        LOGE("---------------methodID isNULL---------------");
        return;
    }
    //调用该java方法
    (*env)->CallStaticVoidMethod(env, clazz, methodID,ret);
}
void callJavaMethodProgress(JNIEnv *env, jclass clazz,float ret) {
    if (clazz == NULL) {
        LOGE("---------------clazz isNULL---------------");
        return;
    }
    //获取方法ID (I)V指的是方法签名 通过javap -s -public FFmpegCmd 命令生成
    LOGE("---------------clazz isNULL--11-------------");
    jmethodID methodID = (*env)->GetStaticMethodID(env, clazz, "onProgress", "(F)V");
    if (methodID == NULL) {
        LOGE("---------------methodID isNULL---------------");
        return;
    }
    //调用该java方法
    (*env)->CallStaticVoidMethod(env, clazz, methodID,ret);
}

void ffmpeg_progress(float progress) {
   // JNIEnv *env;
    //(*jvm)->AttachCurrentThread(jvm, (void **) &env, NULL);
    callJavaMethodProgress(envs, m_clazz,progress);
   // (*jvm)->DetachCurrentThread(jvm);
}


JNIEXPORT jint JNICALL
Java_com_cms_ffmpeg_RxFFmpegInvoke_run(JNIEnv
* env,
jobject thiz, jobjectArray
                                           commands) {

    (*env)->GetJavaVM(env, &jvm);
    envs = env;
    m_clazz = (*env)->GetObjectClass(env,thiz);

    int argc = (*env)->GetArrayLength(env, commands);
    char *argv[argc];

    int i;
    for (i = 0; i < argc; i++) {
        jstring js = (jstring) (*env)->GetObjectArrayElement(env, commands, i);
        argv[i] = (char *) (*env)->GetStringUTFChars(env, js, 0);
    }
   // ffmpeg_thread_run_cmd(argc, argv);
    run(argc,argv);
    return 0 ;
}
